package sunyu.controller;

import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ContextLoader;
import sunyu.toolkit.core.FileKit;
import sunyu.toolkit.core.LogKit;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

/**
 * 文件下载
 *
 * @author 孙宇
 */
@Controller
public class DownloadController {

    private static final Logger logger = LogKit.getLogger();

    /**
     * 坑爹，这个spring封装的ResponseEntity不能用，下载后文件都不能正确解析
     *
     * @param url
     * @return
     * @throws IOException
     */
    /*@RequestMapping("/download2")
    public ResponseEntity<byte[]> download2(String url) throws IOException {
        String path = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath(url);
        String fileName = url.substring(url.lastIndexOf("/") + 1);
        File file = new File(path);//要下载的文件
        String dfileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        byte[] b = FileKit.readBytes(file);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", dfileName);
        headers.setContentLength(b.length);
        return new ResponseEntity<byte[]>(b, headers, HttpStatus.OK);
    }*/


    /**
     * 下载文件
     *
     * @param url      文件相对于WEB项目的地址
     * @param response
     */
    @RequestMapping("/download")
    public void download(String url, HttpServletResponse response) {
        String path = ContextLoader.getCurrentWebApplicationContext().getServletContext().getRealPath(url);
        File file = new File(path);//要下载的文件
        try (OutputStream out = response.getOutputStream();) {
            String dfileName = new String(file.getName().getBytes("UTF-8"), "ISO-8859-1");
            response.reset();
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + dfileName);
            out.write(FileKit.readBytes(file));
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
